package com.ruixun.shopmanagement.controller;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ruixun.shopmanagement.entity.User;
import com.ruixun.shopmanagement.service.inter.UserService;
import com.ruixun.shopmanagement.util.MyDateConvert;

import cn.dsna.util.images.ValidateCode;

@Controller
@RequestMapping("/user")
@ResponseBody
public class UserController {

	@Autowired
	UserService userService;

	/**
	 * 
	 * @Title: checkUserNameExist 检测用户名是否已存在
	 * @Description:
	 * @author: 1246263205@qq.com
	 * @date 2019年12月17日 下午5:26:56
	 * @param uname
	 * @return int
	 * @version
	 */
	@RequestMapping("/checkUserNameExist")
	public int checkUserNameExist(String uname) {
		System.out.println(uname);
		return userService.checkUserNameisExist(uname);
	}

	/**
	 * 
	 * @Title: checkUserEmailExist 检测邮箱是否已存在
	 * @Description:
	 * @author: 1246263205@qq.com
	 * @date 2019年12月18日 上午10:46:02
	 * @param email
	 * @return int
	 * @version
	 */
	@RequestMapping("/checkUserEmailExist")
	public int checkUserEmailExist(String email) {
		System.out.println(email);
		return userService.checkUserEmailisExist(email);
	}

	/**
	 * 
	 * @Title: getVCode 获得随机4位验证码并保存到session
	 * @Description:
	 * @author: anthor
	 * @date 2019年12月5日 上午10:01:19
	 * @param session
	 * @param response void
	 * @version
	 */
	@RequestMapping(value = "/getVeriFicationCode", method = RequestMethod.GET)
	public void getVCode(HttpSession session, HttpServletResponse response) {
		ValidateCode vc = new ValidateCode(120, 30, 4, 13);
		String code = vc.getCode();
		session.setAttribute("vcode", code);
//		5分钟后删除该验证码
//		Timer timer = new Timer();
//		timer.schedule(new TimerTask() {
//			public void run() {
//				if (session.getAttribute("vcode") != null) {
//					session.setAttribute("vcode", null);
//					timer.cancel();
//				}
//			}
//		}, 5 * 60 * 1000);
		try {
			vc.write(response.getOutputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * 
	 * @Title: registerNewUser 注册新用户
	 * @Description:
	 * @author: 1246263205@qq.com
	 * @date 2019年12月19日 上午12:26:03
	 * @param request
	 * @param session
	 * @return Map<String,Object>
	 * @version
	 */
	@RequestMapping(value = "/registerNewUser", method = RequestMethod.POST)
	public Map<String, Object> registerNewUser(HttpServletRequest request, HttpSession session) {
		Map<String, Object> map = new HashMap<>();
		// 首先确认验证码正确
		if (!request.getParameter("code").trim().equalsIgnoreCase((String) session.getAttribute("vcode"))) {
			map.put("message", "注册失败,验证码错误");
			map.put("satte", false);
			return map;
		}

		User user = new User();
		try {
			// 把参数装配进入user对象
			ConvertUtils.register(new MyDateConvert(), java.util.Date.class);
			BeanUtils.populate(user, request.getParameterMap());
			// 确保userservice的名字和邮箱已注册
			if (userService.checkUserEmailisExist(user.getEmail()) == 0
					&& userService.checkUserNameisExist(user.getName()) == 0) {
				if (userService.registerNewUser(user)) {
					map.put("message", "注册成功,请前往邮箱激活账号");
					map.put("state", true);
				} else {
					map.put("message", "注册失败");
					map.put("state", false);
				}
				;
			} else {
				map.put("message", "用户名或邮箱已被注册");
				map.put("state", false);
			}

		} catch (IllegalAccessException | InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return map;
	}

	/**
	 * 
	 * @Title: activeUser 激活账号
	 * @Description:
	 * @author: 1246263205@qq.com
	 * @date 2019年12月19日 上午12:22:36
	 * @param method
	 * @param code
	 * @return Map<String,Object>
	 * @version
	 */
	@RequestMapping(value = "/active", method = RequestMethod.GET)
	public Map<String, Object> activeUser(String method, String code) {
		Map<String, Object> map = new HashMap<>();
		boolean result = userService.activeUser(code);
		if (result) {
			map.put("message", "激活成功");
			System.out.println("激活");
		} else {
			map.put("message", "激活失败");
		}
		return map;
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public Map<String, Object> login(String username, String password, String code, HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> map = new HashMap<>();

		// 首先确认验证码正确
		if (!request.getParameter("code").trim()
				.equalsIgnoreCase((String) request.getSession().getAttribute("vcode"))) {
			map.put("message", "登陆失败,验证码错误");
			map.put("result", false);
			return map;
		}

		// 0判断账号是否存在,或是否激活
		if (userService.checkUserNameisExist(username) != 1) {
			map.put("message", "账号或密码错误");
			map.put("result", false);
			return map;
		}
		if (!userService.checkUserActived(username)) {
			map.put("message", "此账号还未激活");
			map.put("result", false);
			return map;
		}

		// 1,判断是否已经登录
		User user = (User) request.getSession().getAttribute("user");
		if (user == null) {
			// 1.2 没有登录
			// 检查cookie是否需要自动登录
			// 获取所有的cookie
			Cookie[] cookies = request.getCookies();
			if (cookies != null) {
				for (Cookie cookie : cookies) {
					// 判断名字为autoLogin
					if (cookie.getName().equals("autoLogin")) {
						// 获取账号,密码
						String value = cookie.getValue();// username&&&password
						String[] up = value.split("&&&");
						String username2 = up[0];
						String password2 = up[1];
						// 根据用户名密码到数据查询
						user = userService.login(username2, password2);
						// 将用户信息保存到session
						request.getSession().setAttribute("user", user);
						if (user.getName() != null) {
							map.put("message", "欢迎您," + user.getName());
							map.put("username", user.getName());
							map.put("username", user.getName());
							map.put("result", true);
						} else {
							map.put("message", "账号或密码错误");
							map.put("result", false);
						}
						break;
					} else { // cookie手动登陆
						user = userService.login(username, password);
						if (user.getName() != null) {
							map.put("message", "欢迎您," + user.getName());
							map.put("username", user.getName());
							map.put("result", true);
							Cookie c1 = new Cookie("username", "hzh");
							Cookie c2 = new Cookie("password", "123");
							c1.setMaxAge(3600); // 给cookie设置1小时内面登陆
							c2.setMaxAge(3600);
							response.addCookie(c1);
							response.addCookie(c2);
							// 将用户信息保存到session
							request.getSession().setAttribute("user", user);
						}
					}
				}
			} else { // 非cookie登陆
				user = userService.login(username, password);
				if (user.getName() != null) {
					map.put("message", "欢迎您," + user.getName());
					map.put("username", user.getName());
					map.put("result", true);
					Cookie c1 = new Cookie("username", "hzh");
					Cookie c2 = new Cookie("password", "123");
					c1.setMaxAge(3600); // 给cookie设置1小时内面登陆
					c2.setMaxAge(3600);
					response.addCookie(c1);
					response.addCookie(c2);
					// 将用户信息保存到session
					request.getSession().setAttribute("user", user);
				} else {
					map.put("message", "账号或密码错误");
					map.put("result", false);
				}

			}

		} else {
			map.put("result", true);
			map.put("message", "欢迎您," + user.getName());
			map.put("username", user.getName()); // 已登陆
		}
		return map;
	}

	// 已登陆
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public Map<String, Object> login(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<>();
		// 1,判断是否已经登录
		User user = (User) request.getSession().getAttribute("user");
		if (user == null) {
			// 1.2 没有登录
			// 检查cookie是否需要自动登录
			// 获取所有的cookie
			Cookie[] cookies = request.getCookies();
			if (cookies != null) {
				for (Cookie cookie : cookies) {
					// 判断名字为autoLogin
					if (cookie.getName().equals("autoLogin")) {
						// 获取账号,密码
						String value = cookie.getValue();// username&&&password
						String[] up = value.split("&&&");
						String username2 = up[0];
						String password2 = up[1];
						// 根据用户名密码到数据查询
						user = userService.login(username2, password2);
						// 将用户信息保存到session0=
						request.getSession().setAttribute("user", user);
						if (user.getName() != null) {
							map.put("message", "欢迎您," + user.getName());
							map.put("username", user.getName());
							map.put("result", true);
						} else {
							map.put("message", "账号或密码错误");
							map.put("result", false);
						}
						break;
					}
				}
			}
		} else {
			map.put("result", true);
			map.put("message", "欢迎您," + user.getName());
			map.put("username", user.getName()); // 已登陆
		}
		return map;
	}

	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public boolean logout(HttpServletRequest request, HttpServletResponse response) {
		// 清空session/cookie
		request.getSession().invalidate();
		Cookie cookie = new Cookie("autoLogin", "");
		cookie.setMaxAge(0);
		response.addCookie(cookie);
		return true;
	}

}
